<template>
  <ul class="list">
    <li class="item"
        v-for="(item,index) of cities"
        :key="index"
        @click="letterClick"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        :ref="index"
    >{{index}}
    </li>

  </ul>
</template>

<script>
  export default {
    name: "city-alphabet",
    props: ['cities'],
    data() {
      return {
        touchStatus: false,
        top2A: 0,
        timer: null
      }
    },
    updated(){//当数据被更新的时候执行以下代码
      this.top2A=this.$refs['A'][0].offsetTop;
    }
  ,
  computed: {
    letters()
    {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  }
  ,
  methods: {
    letterClick(e)
    {
      this.$emit('letterChange', e.target.innerText);
    }
  ,
    //dom元素的3个内置事件 touchStart(手指点击下去初始化) touchMove（按住拖动） touchEnd（手指抬起）,要一起使用
    handleTouchStart()
    {
      this.touchStatus = true;
    }
  ,
    handleTouchMove(e)
    {
      if (this.touchStatus === true) {
        if (this.timer){
          clearTimeout(this.timer)
        }
        //当鼠标移动是以很高的频率执行handleTouchMove(e)方法，这样很浪费资源，所以设置一个延迟方法，减缓方法执行的频率
        this.timer= setTimeout(()=>{
          let WindowTop2finger = e.touches[0].clientY;//当时一根手指（一个触点）到屏幕顶点的长度
          let top2finger = WindowTop2finger - 79;//到边栏定点的距离
          let index = Math.floor((top2finger - this.top2A) / 20);//得到A到D（假设）的长度，再除以行高，得到索引
          if (index >= 0 && index < this.letters.length) {
            this.$emit('letterChange', this.letters[index])
          }
        },16)
      }
    }
  ,
    handleTouchEnd()
    {
      this.touchStatus = false;
    }
  }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/variable.styl"
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
